# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_auth.py
# @Time      :2022/5/30 0030 15:14
# @Author    :何胜利
import redis
from flask import request, g

from common.utils.jwt_util import verify_jwt, _generate_token


def jwt_authentication():
    """
    验证token
    在获取用户信息前验证前端发起请求携带的token,是否和后端生成的一样
    """
    g.user_id = None
    g.is_refresh = False

    token = request.headers.get('Authorization')
    print("校验的token--", token)
    if token:
        payload = verify_jwt(token)
        print("auth payload---->", payload)
        if payload:
            # token 校验成功, 把用户id 写入g 对象
            print("user_id-----", payload.get)
            g.user_id = payload.get("user_id", None)
            g.is_refresh = payload.get("is_refresh", False)

            rdb = redis.Redis(db=8)
            rdb_token = rdb.get("user:%s:token"% g.user_id)
            if rdb_token:
                if token != rdb_token.decode('utf-8'):
                    return {"message": "没有权限访问", "code": 406}
            else:
                pass

        else:
            payload_ = {"refresh": True}
            _, refresh_token = _generate_token(payload_, refresh=True)
            request.headers["Authorization"] = refresh_token

